package com.hou.netty.helloworld.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

//客户端处理数据
public class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private int lossConnectCount = 0;

    //处理服务端返回的数据
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] data = new byte[byteBuf.readableBytes()];//byteBuf.readableBytes():获取可用的长度
        byteBuf.readBytes(data);//数据读取到数组中
        String string = new String(data, "utf-8");
        System.out.println("客户端接受到服务端返回的数据:" + string);
        //ReferenceCountUtil.release(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();//打印信息
        ctx.close();//关闭通道
    }

    //心跳检测
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("5秒了,超时");
        if (evt instanceof IdleStateEvent) {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                // WRITER_IDLE :写空闲事件  All_IDLE :所有类型空闲事件
                if (event.state() == IdleState.READER_IDLE) {//判断是否读空闲事件
                    //逻辑处理
                    lossConnectCount++;
                    if (lossConnectCount > 2) {  //超过两次空闲就关闭通道
                        System.out.println("关闭这个不活跃通道！");
                        ctx.channel().close();
                    }
                }
            } else {
                // 传递给下一个处理程序
                super.userEventTriggered(ctx, evt);
            }
        }
    }
}
